package com.getpebble.android.framework.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.framework.notification.gmail.GmailCheckerService;
import com.getpebble.android.notifications.util.CoreNotifications;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class GmailReceiver extends BroadcastReceiver {
    private static final String TAG = GmailReceiver.class.getSimpleName();
    private static final long THRESHOLD = TimeUnit.SECONDS.toMillis(2);
    private static AtomicLong lastReceivedAt = new AtomicLong(0);

    public void onReceive(Context context, Intent intent) {
        if (CoreNotifications.allowGmailImapNotifications()) {
            Trace.verbose(TAG, "received a 'new message' intent from Gmail");
            if (context == null) {
                Trace.verbose(TAG, "onReceive: context was null");
                return;
            }
            long now = System.currentTimeMillis();
            if (now - lastReceivedAt.getAndSet(now) < THRESHOLD) {
                Trace.verbose(TAG, "received back-to-back gmail notification");
                return;
            }
            PblPreferences prefs = new PblPreferences(context.getApplicationContext());
            String account = intent.getStringExtra(GmailCheckerService.EXTRA_ACCOUNT);
            if (prefs.getSharedPreferences().getBoolean(prefs.prefKeyToString(PrefKey.GMAIL_ACCOUNT_ENABLED_PREFIX) + account, false)) {
                Trace.verbose(TAG, "Gmail intent received; dispatching checker intent, received=" + intent.toUri(1));
                int count = intent.getIntExtra(GmailCheckerService.EXTRA_COUNT, 0);
                Intent checkerIntent = new Intent(context, GmailCheckerService.class);
                checkerIntent.putExtra(GmailCheckerService.EXTRA_ACCOUNT, account);
                checkerIntent.putExtra(GmailCheckerService.EXTRA_COUNT, count);
                Trace.verbose(TAG, "Dispatched a job to the GmailChecker");
                context.startService(checkerIntent);
                return;
            }
            Trace.verbose(TAG, "Account " + account + " is not enabled; skipping");
            return;
        }
        Trace.verbose(TAG, "gmail IMAP disabled on this Android version");
    }

    public static Intent buildUpdateIntent(String account, int count) {
        Intent i = new Intent("com.getpebble.action.UPDATE_GMAIL_ACCOUNT");
        i.putExtra(GmailCheckerService.EXTRA_ACCOUNT, account);
        i.putExtra(GmailCheckerService.EXTRA_COUNT, count);
        return i;
    }
}
